﻿using com.iot.core.boot;
using com.iot.core.exception;
using CSRedis;
using System.Data;
using System.Data.SqlClient;

namespace com.iot.ht.Controllers.htsoft.service
{
    public class AppCheckSqlServer : AppCheck
    {
        SqlConnection conn = null;
        SqlCommand cmd = null;
        string connectionString = "";
        string cmdsql = "";
        
        public override async Task<MyApiResult> Check()
        {
            var r = new MyApiResult();
            try
            {
                if (connectionString == "")
                {
                    connectionString = HtSoftApp.CkArg1; 
                    if (connectionString.IndexOf("Connect Timeout=") < 0)
                    {
                        connectionString += ";Connect Timeout=4;";
                    }
                    cmdsql = HtSoftApp.CkArg2;
                    if (string.IsNullOrEmpty(cmdsql))
                    {
                        cmdsql = "select getdate()";
                    }
                }

                if (conn == null)
                {
                    conn = new SqlConnection(connectionString);
                    conn.Open();
                    cmd = new SqlCommand(cmdsql, conn);
                    cmd.CommandTimeout = 5000;
                }
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }

                r.Msg = cmd.ExecuteScalar().ToString();
                 
            }
            catch (Exception ex)
            {
                r.Code = 1;
                r.Msg = MyExceptionUtil.GetExMsg(ex);


                //conn.Dispose();
                //cmd.Dispose();
                //conn = null;
                //cmd = null;

            }
            return r;
        }
    }
}
